package com.ppt.android.activity

import android.view.View
import android.widget.Toast
import androidx.activity.viewModels
import com.ppt.android.R
import com.ppt.android.activity.vm.MainViewModel
import com.ppt.android.base.BaseActivity
import com.ppt.android.common.adapter.ViewPagerAdapter
import com.ppt.android.databinding.ActivityMainBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlin.system.exitProcess

@AndroidEntryPoint
class MainActivity : BaseActivity<ActivityMainBinding, MainViewModel>() {

    private var backPressedTime: Long = 0
    private var isShowAd = false
    companion object {
        const val INDEX_HOME = 0
        const val INDEX_PHRASE = 1
        const val INDEX_HISTORY = 2

    }

    private val mVpAdapter by lazy(mode = LazyThreadSafetyMode.NONE) {
        ViewPagerAdapter(this, mViewModel.fragments)
    }

    override fun ActivityMainBinding.initView() {
        mBinding.viewpageMain.run {
            adapter = mVpAdapter
            setPageTransformer(null)
            isUserInputEnabled = false
        }
        mBinding.viewpageMain.setCurrentItem(INDEX_HOME, false)
        mBinding.tvTabHome.isSelected = true
    }

    override val mViewModel by viewModels<MainViewModel>()

    override fun initObserve() {
        mBinding.llTabHome.setOnClickListener(this::onClickListener)
        mBinding.llTabEcommerce.setOnClickListener(this::onClickListener)
        mBinding.llTabMine.setOnClickListener(this::onClickListener)

    }

    override fun initRequestData() {

        //show banner
//        CoreManager.getInstance()
//            .showBn(this@MainActivity, "main", m)
    }

    private fun onClickListener(view: View) {
        clearSelect()
        when (view.id) {
            R.id.ll_tab_home -> {
                mBinding.tvTabHome.isSelected = true
                mBinding.viewpageMain.setCurrentItem(INDEX_HOME, false)
            }

            R.id.ll_tab_ecommerce -> {
                mBinding.tvTabEcommerce.isSelected = true
                mBinding.viewpageMain.setCurrentItem(INDEX_PHRASE, false)

            }

            R.id.ll_tab_mine -> {
                mBinding.tvTabMine.isSelected = true
                mBinding.viewpageMain.setCurrentItem(INDEX_HISTORY, false)
            }

            else -> {}

        }
    }

    private fun clearSelect() {
        mBinding.tvTabHome.isSelected = false
        mBinding.tvTabEcommerce.isSelected = false
        mBinding.tvTabMine.isSelected = false
    }

    override fun onBackPressed() {
        if(isShowAd){
            return
        }
        if (backPressedTime + 2000 > System.currentTimeMillis()) {
            // 如果两次按下的时间间隔小于 2 秒，则退出程序
            exitProcess(0)
        } else {
            // 提示用户再按一次退出
            Toast.makeText(this, "Press again to exit the program", Toast.LENGTH_SHORT).show()
        }
        // 更新按下返回键的时间
        backPressedTime = System.currentTimeMillis()
    }

}